//
//  RegistViewController.m
//  SsehMaster
//
//  Created by 杨阳 on 2018/8/3.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "RegistViewController.h"

#import "RSA.h"

@interface RegistViewController ()

@property(nonatomic,strong) UITextField * phoneTF, * passWordTF , *verifiTF;

@property (nonatomic,strong) UIButton * registButton ,* verifiButton;

@end

static NSInteger numTime;

@implementation RegistViewController{
    
    dispatch_source_t _labelTimer;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"注册";
    numTime = 0;
    [self layoutUI];
}

-(void)layoutUI{
    
    __weak typeof (self)weakSelf = self;
    //手机号
    UIView * phoneView = [UIView new];
    phoneView.layer.borderColor = [UIColor viewLayerGray].CGColor;
    phoneView.layer.borderWidth = 0.5f;
    phoneView.layer.cornerRadius = 5;
    [self.view addSubview:phoneView];
    [phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top).offset(20+NAVIGATION_BAR_HEIGHT);
        make.left.equalTo(weakSelf.view.mas_left).offset(10*PROPORTION_WIDTH_IPHONE6);
        make.right.equalTo(weakSelf.view.mas_right).offset(-10*PROPORTION_WIDTH_IPHONE6);
        make.height.mas_equalTo(50);
    }];
    
    self.phoneTF = [UITextField new];
    self.phoneTF.placeholder = @"请输入您的手机号";
    self.phoneTF.text = self.phoneStr;
    self.phoneTF.keyboardType = UIKeyboardTypePhonePad;
    self.phoneTF.textColor = [UIColor textGrayColor];
    self.phoneTF.font = [UIFont systemFontOfSize:14];
    [self.phoneTF setValue:[UIFont boldSystemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    [phoneView addSubview:self.phoneTF];
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(phoneView).offset(15);
        make.top.bottom.right.equalTo(phoneView);
    }];
    
    //验证码
    
    UIView * verifiView = [UIView new];
    verifiView.layer.borderColor = [UIColor viewLayerGray].CGColor;
    verifiView.layer.borderWidth = 0.5f;
    verifiView.layer.cornerRadius = 5;
    [self.view addSubview:verifiView];
    [verifiView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(phoneView.mas_bottom).offset(10);
        make.left.right.equalTo(phoneView);
        make.height.mas_equalTo(50);
    }];
    
    self.verifiButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.verifiButton.titleLabel.font = [UIFont systemFontOfSize:14];
    self.verifiButton.layer.cornerRadius = 7;
    [self.verifiButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.verifiButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.verifiButton setBackgroundColor:[UIColor appColor]];
    [self.verifiButton addTarget:self action:@selector(verifiButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [verifiView addSubview:self.verifiButton];
    [self.verifiButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(verifiView.mas_centerY);
        make.right.equalTo(verifiView.mas_right).offset(-10);
        make.size.mas_equalTo(CGSizeMake(90, 30));
    }];
    
    
    self.verifiTF = [UITextField new];
    self.verifiTF.placeholder = @"请输入您的验证码";
    self.verifiTF.textColor = [UIColor textGrayColor];
    self.verifiTF.font = [UIFont systemFontOfSize:14];
    self.verifiTF.keyboardType = UIKeyboardTypePhonePad;
    [self.verifiTF setValue:[UIFont boldSystemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    [verifiView addSubview:self.verifiTF];
    [self.verifiTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.verifiButton.mas_left).offset(-2);
        make.left.equalTo(verifiView).offset(15);
        make.top.bottom.equalTo(verifiView);
    }];
    
    //密码
    
    UIView * pwView = [UIView new];
    pwView.layer.borderColor = [UIColor viewLayerGray].CGColor;
    pwView.layer.borderWidth = 0.5f;
    pwView.layer.cornerRadius = 5;
    [self.view addSubview:pwView];
    [pwView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(verifiView.mas_bottom).offset(10);
        make.left.right.equalTo(phoneView);
        make.height.mas_equalTo(50);
    }];
    
    self.passWordTF = [UITextField new];
    self.passWordTF.placeholder = @"请输入您的密码";
    self.passWordTF.secureTextEntry = YES;
    self.passWordTF.textColor = [UIColor textGrayColor];
    self.passWordTF.font = [UIFont systemFontOfSize:14];
    [self.passWordTF setValue:[UIFont boldSystemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    [pwView addSubview:self.passWordTF];
    [self.passWordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(pwView).offset(15);
        make.top.bottom.right.equalTo(pwView);
    }];
    
    //注册
    
    self.registButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.registButton.titleLabel.font = [UIFont systemFontOfSize:16];
    self.registButton.layer.cornerRadius = 7;
    [self.registButton setBackgroundColor:[UIColor appColor]];
    [self.registButton setTitle:@"注册" forState:UIControlStateNormal];
    [self.registButton addTarget:self action:@selector(registButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.registButton];
    [self.registButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(pwView.mas_bottom).offset(16);
        make.leading.trailing.equalTo(pwView);
        make.height.mas_equalTo(47);
    }];
    
}

//验证码

-(void)verifiButtonClick:(UIButton *)button{
    
    if (self.phoneTF.text.length != 11) {
        [self showErrorTipWithTitle:@"手机号码格式错误！"];
        return;
    }
    
    [self showLoading];
    
    NSDictionary * par = @{@"mobile":[RSA encryptString:self.phoneTF.text publicKey:SsehRsaPublicKey],@"code_type":[RSA encryptString:@"register" publicKey:SsehRsaPublicKey]};
    [[QYNetManager sharedManager]POST:kSendCode parameters:par andApiTyp:SsehApiTypMain SuccessBlock:^(id responseObject) {
        [self hideLoading];
        NSString * statusStr = [NSString stringWithFormat:@"%@",responseObject[@"status"]];
        if ([statusStr isEqualToString:@"ok"]) {
            numTime = 60;
            [self startTimer];
        }else{
            NSString * errorStr = [NSString stringWithFormat:@"%@",responseObject[@"error"]];
            [self showErrorTipWithTitle:errorStr];
        }
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showErrorTipWithTitle:SsehPoolNetStr];
    }];

    
}

//注册
-(void)registButtonClick:(UIButton *)button{
    
    if (self.phoneTF.text.length != 11) {
        [self showErrorTipWithTitle:@"手机号码格式错误！"];
        return;
    }
    
    if (self.verifiTF.text.length != 6) {
        [self showErrorTipWithTitle:@"验证码输入错误"];
        return;
    }
    
    if (self.passWordTF.text.length < 8 ) {
        [self showErrorTipWithTitle:@"密码长度至少8位"];
        return;
    }
    [self showLoading];
    NSDictionary * par = @{@"member_account":self.phoneTF.text,@"member_password":self.passWordTF.text,@"code":self.verifiTF.text,@"member_type":@"2"};
    [[QYNetManager sharedManager]POST:kRegisterMember parameters:par andApiTyp:SsehApiTypMain SuccessBlock:^(id responseObject) {
        [self hideLoading];
        NSString * statusStr = [NSString stringWithFormat:@"%@",responseObject[@"status"]];
        if ([statusStr isEqualToString:@"ok"]) {
            [self showTipWithTitle:@"注册成功"];
            [self performSelector:@selector(backLogin) withObject:nil afterDelay:1.0f];
        }else{
            NSString * errorStr = [NSString stringWithFormat:@"%@",responseObject[@"error"]];
            [self showErrorTipWithTitle:errorStr];
        }
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showErrorTipWithTitle:SsehPoolNetStr];
    }];
    
}

-(void)backLogin{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 定时器
//开启定时器

-(void)startTimer{
    
    if (_labelTimer == nil) {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _labelTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(_labelTimer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);//每秒执行
        dispatch_source_set_event_handler(_labelTimer, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self changeTime];
            });
        });
        dispatch_resume(_labelTimer);//启动定时器
    }
}

-(void)changeTime{
    
    if (numTime == 0) {
        [self destoryLabelTimer];
        [self.verifiButton setTitle:@"重新获取" forState:UIControlStateNormal];
        self.verifiButton.userInteractionEnabled = YES;
        [self.verifiButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        return;
    }
    
    numTime -= 1;
    self.verifiButton.userInteractionEnabled = NO;
    [self.verifiButton setTitle:[NSString stringWithFormat:@"%ld",numTime] forState:UIControlStateNormal];
}

//销毁定时器
- (void)destoryLabelTimer{
    
    if (_labelTimer) {
        dispatch_source_cancel(_labelTimer);
        _labelTimer = nil;
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
